import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

/**
 * 链路追踪服务
 * 提供请求追踪和性能监控功能
 */
@Injectable()
export class TracingService {
  private readonly logger = new Logger(TracingService.name);

  constructor(private readonly configService: ConfigService) {}

  /**
   * 开始追踪
   */
  startTrace(traceId: string, operation: string) {
    const startTime = Date.now();
    this.logger.log(`[${traceId}] Starting ${operation} at ${startTime}`);

    return {
      traceId,
      operation,
      startTime,
    };
  }

  /**
   * 结束追踪
   */
  endTrace(trace: any, result?: any) {
    const endTime = Date.now();
    const duration = endTime - trace.startTime;

    this.logger.log(
      `[${trace.traceId}] Completed ${trace.operation} in ${duration}ms`,
    );

    if (result) {
      this.logger.debug(`[${trace.traceId}] Result: ${JSON.stringify(result)}`);
    }

    return {
      ...trace,
      endTime,
      duration,
      result,
    };
  }

  /**
   * 记录错误
   */
  recordError(trace: any, error: Error) {
    const endTime = Date.now();
    const duration = endTime - trace.startTime;

    this.logger.error(
      `[${trace.traceId}] Error in ${trace.operation} after ${duration}ms: ${error.message}`,
    );

    return {
      ...trace,
      endTime,
      duration,
      error: error.message,
    };
  }

  /**
   * 生成追踪 ID
   */
  generateTraceId(): string {
    return `trace_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }
}
